import socket
import threading
import os
import tkinter as tk
from tkinter import messagebox

HOST = ''
PORT = 8080
BUF_SIZE = 4096
OTA_FILE_PATH = 'bin/ota.bin'

def send_ota_file(conn, filename):
    print(f"[INFO] 客户端请求OTA文件: {filename}")
    # 界面显示已连接
    if hasattr(send_ota_file, 'info_label'):
        send_ota_file.info_label.config(text="已连接，正在发送文件...")
    if not os.path.exists(filename):
        not_found = "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n"
        conn.sendall(not_found.encode())
        # 弹窗提醒
        messagebox.showerror("文件未找到", f"未找到OTA文件: {filename}")
        return
    filesize = os.path.getsize(filename)
    header = (
        "HTTP/1.1 200 OK\r\n"
        "Content-Type: application/octet-stream\r\n"
        f"Content-Length: {filesize}\r\n"
        "Content-Disposition: attachment; filename=\"ota.bin\"\r\n"
        "Connection: close\r\n\r\n"
    )
    conn.sendall(header.encode())
    total = 0
    with open(filename, 'rb') as f:
        while True:
            chunk = f.read(BUF_SIZE)
            if not chunk:
                break
            conn.sendall(chunk)
            total += len(chunk)
    print(f"[INFO] 已发送OTA文件，总字节数: {total}")
    # 界面显示已发送完成
    if hasattr(send_ota_file, 'info_label'):
        send_ota_file.info_label.config(text="已发送完成，2秒后自动退出...")
    # 等待2秒后退出主程序
    import time
    time.sleep(2)
    os._exit(0)

def handle_client(conn, addr):
    print(f"[INFO] 客户端已连接: {addr}")
    try:
        buffer = conn.recv(1024).decode(errors='ignore')
        print(f"[INFO] 收到请求:\n{buffer}")
        if "GET /bin/ota.bin" in buffer or "GET //bin/ota.bin" in buffer:
            send_ota_file(conn, OTA_FILE_PATH)
        else:
            print("[WARN] 未知请求，返回404")
            not_found = "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n"
            conn.sendall(not_found.encode())
    except Exception as e:
        print(f"[ERROR] 处理客户端异常: {e}")
    finally:
        conn.close()
        print("[INFO] 客户端连接已关闭")

def main():
    root = tk.Tk()
    root.title("科奈信8735b升级程序")
    root.geometry("400x200")
    status_label = tk.Label(root, text=f"服务器端口: {PORT}", font=("Arial", 14))
    status_label.pack(pady=20)
    info_label = tk.Label(root, text="等待客户端连接...", font=("Arial", 12))
    info_label.pack(pady=10)

    # 启动时判断文件是否存在
    if not os.path.exists(OTA_FILE_PATH):
        messagebox.showerror("文件未找到", f"未找到OTA文件: {OTA_FILE_PATH}")
        root.destroy()
        return

    def server_thread_func():
        send_ota_file.info_label = info_label
        server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        server_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        server_sock.bind((HOST, PORT))
        server_sock.listen(5)
        print(f"OTA HTTP服务器已启动，端口{PORT}")
        while True:
            info_label.config(text="等待客户端连接...")
            conn, addr = server_sock.accept()
            info_label.config(text=f"客户端已连接: {addr}")
            threading.Thread(target=handle_client, args=(conn, addr), daemon=True).start()

    threading.Thread(target=server_thread_func, daemon=True).start()
    root.mainloop()

if __name__ == '__main__':
    main()
